import { ScreenContainer } from "components/lib";
import { useProjectInUrl } from "screens/kanban/util";
import { Button, List, Modal } from "antd";
import { useDeleteEpic, useEpics, useTasks } from "server";
import { Row } from "components/lib";
import { formatDate } from "utils";
import { Link } from "react-router-dom";
import { EpicType } from "types";

const Epic = () => {
  const { data: currentProject } = useProjectInUrl();
  const { data: epics } = useEpics();
  const { data: tasks } = useTasks({ projectId: currentProject?.id });
  const { mutateAsync: deleteEpic } = useDeleteEpic();

  const onDelete = (id: number, name: string) => {
    Modal.confirm({
      title: `确定删除项目组：${name}`,
      okText: "确定",
      cancelText: "取消",
      onOk: () => deleteEpic(id),
    });
  };

  const renderItem = (epic: EpicType) => (
    <List.Item>
      <List.Item.Meta
        title={
          <Row between>
            <span>{epic.name}</span>
            <Button type="link" onClick={() => onDelete(epic.id, epic.name)}>
              删除
            </Button>
          </Row>
        }
        description={
          <div>
            <div>开始时间：{formatDate(epic.start)}</div>
            <div>结束时间：{formatDate(epic.end)}</div>
            <div>
              {tasks
                ?.filter((t) => t.epicId === epic.id)
                .map((t) => (
                  <Link
                    key={t.id}
                    to={`/project/${currentProject?.id}/kanban?editingTaskId=${t.id}`}
                  >
                    {t.name}
                  </Link>
                ))}
            </div>
          </div>
        }
      />
    </List.Item>
  );

  return (
    <ScreenContainer>
      <h1>{currentProject?.name}任务组</h1>
      <List dataSource={epics} itemLayout="vertical" renderItem={renderItem} />
    </ScreenContainer>
  );
};

export default Epic;
